<template>
	<div class="aid">
		<div class="base">
			<p>
				头像上传
				<a-icon @click="closeFunction" :style="{ float: 'right', margin: '10px','font-size':'26px' }"
					type="close-circle" />
			</p>
			<a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
				<a-form-model-item label="选择图片">
					<a-upload :file-list="fileList" :remove="handleRemove" @preview="handlePreview"
						list-type="picture-card"
						v-decorator="['headImage', { rules: [{ required: true, message: '请先上传一张图片' }] }]"
						accept="image/*" :before-upload="beforeUpload" @change="handleChange">

						<div class="upload-btn" v-if="fileList.length < 1">
							<span>↥</span>
							<div class="ant-upload-text">上传头像</div>
						</div>

					</a-upload>

				</a-form-model-item>
				<div class="btn fixed-bottom">
					<a-button type="primary" class="btn2" @click="handleSubmit">确定</a-button>
					<a-button style="margin-left: 10px;" @click="closeFunction">取消</a-button>
				</div>
			</a-form-model>
			<el-dialog title="图片裁剪" :visible.sync="dialogStatusVisible" @open="cropperOpen">
				<div style="margin-top:20px;height:400px;">
					<div class="cropper" style="text-align:center;height:400px;">
						<vueCropper ref="cropper" :img="option.img" :outputSize="option.outputSize"
							:outputType="option.outputType" :info="option.info" :canScale="option.canScale"
							:autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth"
							:autoCropHeight="option.autoCropHeight" :fixed="option.fixed" :fixedBox="option.fixedBox"
							:fixedNumber="option.fixedNumber"></vueCropper>
					</div>
				</div>
				<span slot="footer" class="dialog-footer">
					<el-button class="btn closebtn" plain @click.stop="cancelStatus">取消</el-button>
					<el-button class="btn surebtn" type="primary" @click.stop="sureStatus">确认</el-button>
				</span>
			</el-dialog>
		</div>
		<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
			<img alt="example" style="width: 100%" :src="previewImage" />
		</a-modal>
	</div>
</template>

<script>
	function getBase64(img, callback) {
		const reader = new FileReader();
		reader.addEventListener('load', () => callback(reader.result));
		reader.readAsDataURL(img);
	}
	import {
		UserDoSetHeadImage,
		UserDoUpdateBase64Image,
		GetUserInfo
	} from '@/api/follow';
	import Cache from '@/utils/cache'
	import {
		VueCropper
	} from 'vue-cropper'
	export default {
		components: {
			VueCropper
		},
		props: {
			// num:Number
		},
		watch: {
			text: function(text) {
				this.form.linkurl = '';
				this.fileList = [];
			}
		},
		data() {
			return {
				dialogStatusVisible: false,
				option: {
					img: '', // 裁剪图片的地址
					info: true, // 裁剪框的大小信息
					outputSize: 1, // 裁剪生成图片的质量
					outputType: 'png', // 裁剪生成图片的格式
					canScale: false, // 图片是否允许滚轮缩放
					autoCrop: true, // 是否默认生成截图框
					autoCropWidth: 212, // 默认生成截图框宽度
					autoCropHeight: 212, // 默认生成截图框高度
					fixedBox: false, // 固定截图框大小 不允许改变
					fixed: true, // 是否开启截图框宽高固定比例
					fixedNumber: [1, 1], // 截图框的宽高比例
					full: false, // 是否输出原图比例的截图
					canMoveBox: true, // 截图框能否拖动
					original: true, // 上传图片按照原始比例渲染
					centerBox: false, // 截图框是否被限制在图片里面
					infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
					canMove: true,
				},
				labelCol: {
					span: 4
				},
				wrapperCol: {
					span: 14
				},
				formLayout: 'horizontal',
				form: this.$form.createForm(this, {
					name: 'coordinated'
				}),
				headImage: '',
				fileList: [],
				formLayout: 'horizontal',
				form: {
					linkurl: '',
					ImageTypeID: '',
					Name: '',
					Url: ''
				},
				typedata: [],
				addshow: false,
				typename: '',
				loading: false,
				imageUrl: '',
				ticket: Cache.get('token'),
				rules: {
					ImageTypeID: [{
						required: true,
						message: '请选择类别',
						trigger: 'change'
					}]
				},
				previewVisible: false,
				previewImage: '',
				requestUrl: this.global.requestUrl
			};
		},
		async created() {},
		methods: {
			sureStatus() {
				// 获取截图的 blob 数据
				this.$refs.cropper.getCropBlob((blob) => {
					this.dialogStatusVisible = false
				})
				// 获取截图的 base64 数据
				this.$refs.cropper.getCropData(data => {
					// console.log("获取 base64 数据:", data)
					this.headImage = this.fileList[0].url = data
				})
			},
			async cancelStatus() {
				this.dialogStatusVisible = false
				this.imageUrlToBase64(this.fileList[0].url)
			},
			imageUrlToBase64(imageUrl) {
				//一定要设置为let，不然图片不显示
				let image = new Image();
				//解决跨域问题
				image.setAttribute('crossOrigin', 'anonymous');
				image.src = imageUrl
				let that = this;
				//image.onload为异步加载S
				image.onload = () => {
					var canvas = document.createElement("canvas");
					canvas.width = image.width;
					canvas.height = image.height;
					var context = canvas.getContext('2d');
					context.drawImage(image, 0, 0, image.width, image.height);
					var quality = 0.8;
					//这里的dataurl就是base64类型
					that.headImage = canvas.toDataURL("image/jpeg",
					quality); //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
				}
			},
			cropperOpen() {
				this.option.img = this.fileList[0].url
			},
			handleCancel() {
				this.previewVisible = false;
			},
			async handlePreview(file) {
				let nameType = file.name.substr(file.name.lastIndexOf('.') + 1)
				if (this.global.imgTypeList.findIndex(m => {
						return m == nameType
					}) < 0) {
					this.$message.error('该文件格式不支持预览')
					return false
				}
				if (!file.url && !file.preview) {
					file.preview = await getBase64(file.originFileObj);
				}
				this.previewImage = file.url || file.preview;

				this.previewVisible = true;
			},
			handleRemove(file) {
				const index = this.fileList.indexOf(file);
				const newFileList = this.fileList.slice();
				newFileList.splice(index, 1);
				this.fileList = newFileList;
			},
			async handleSubmit(e) {
				e.preventDefault();
				this.$refs.ruleForm.validate(async valid => {
					if (valid) {
						let data1 = {}
						data1.headImage = this.headImage
						Promise.resolve(UserDoSetHeadImage(data1)).then((m) => {
							if (m.data.code == 0) {
								this.$message.success(m.data.msg)
								let session = Cache.get('myInfo')
								session.HeadImage = this.headImage
								Cache.set('myInfo', session);
								this.$emit('closeFun', 2);
							}
						})
						// let res=UserDoSetHeadImage(data1)
						// if(res.data.code==0){
						// 		that.$message.success(res.data.msg)
						// 		this.$emit('closeFun');
						// 	}

					} else {
						return false;
					}
				});
			},
			closeFunction(data) {
				this.$emit('closeFun');
				this.form = {}
				this.imageUrl = ''
				this.fileList = []
			},
			beforeUpload(file) {
				this.fileList = [...this.fileList, file];
			},
			async handleChange(info) {
				if (info.file.originFileObj) {
					getBase64(info.file.originFileObj, imageUrl => {
						this.imageUrl = imageUrl;
						let data = {}
						let newbase = this.imageUrl
						let base = newbase.lastIndexOf("\,")
						newbase = newbase.substring(base + 1, newbase.length)
						data.data = newbase
						Promise.resolve(UserDoUpdateBase64Image(data)).then((v) => {
							this.headImage = v.data.url
							let list = [{
								uid: -1,
								name: this.fileList[0].name,
								status: 'done',
								url: this.requestUrl + this.headImage
							}]
							this.dialogStatusVisible = true
							this.fileList = list
						})
					});
				} else {
					return false
				}

			},
		}
	};
</script>

<style lang="less" scoped>
	.btnclose {
		text-align: center;
	}

	/deep/.el-dialog__header {
		display: none;
	}

	/deep/ .ant-upload-list-item {
		width: 300px !important;
		height: 300px !important;
	}

	.aid {
		position: fixed;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
		top: 0px;
		left: 0px;
		z-index: 999;
	}

	.base {
		position: relative;
		width: 600px;
		height: 300px;
		background: #fff;
		left: 50%;
		top: 50%;
		margin-left: -300px;
		margin-top: -150px;
		overflow-y: auto;

		/deep/.ant-form-item {
			margin: 20px 50px;

			/deep/.ant-form-item-label {
				width: 100px;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				text-align: right;
			}

			/deep/.ant-form-item-control-wrapper {
				flex: 1;
			}
		}
	}

	.base p {
		padding: 10px 0 0 10px;
	}

	.subnav {
		margin-left: 60px;
		height: 46px;
		display: flex;
	}

	.subnav p {
		width: 100px;
		text-align: right;
	}

	.subnav input {
		width: 300px;
		height: 30px;
		border: 1px solid #dad9dc;
		margin-left: 20px;
	}

	.ant-form-item {
		margin-bottom: 10px;
	}

	.titletip {
		padding-left: 10px;
		font-size: 12px;
		color: red;
	}

	.btn {
		margin-top: 10px;
		text-align: center;
	}

	.addtype {
		color: #1890ff;
	}

	.addtype:hover {
		cursor: pointer;
	}

	.mbzz {
		position: fixed;
		top: 0px;
		left: 0px;
		bottom: 0px;
		right: 0px;
		background: rgba(0, 0, 0, 0.5);
		z-index: 999;
	}

	.addimgtype {
		width: 30rem;
		text-align: center;
		border: 1px solid gray;
		position: absolute;
		top: 50%;
		left: 50%;
		background: #ffffff;
		height: 14rem;
		z-index: 999;
		margin-top: -7rem;
		margin-left: -15rem;

		p {
			padding: 10px 0 0 10px;
		}
	}

	.titletip {
		padding-left: 10px;
		font-size: 12px;
		color: red;
	}
</style>
